local httpc=require"http.httpc"
local json=require"cjson"

function httpc.post_json(host, url, form, recvheader)
	local header = {
		["content-type"] = "application/json",
	}

	local body
	if type(form) == "string" then
		body=form
	else
		body=json.encode(form)
	end
	return httpc.request("POST", host, url, recvheader, header, body)
end

function httpc.post_form(host, url, form, recvheader)
	local header = {
		["content-type"] = "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
	}

	local body=""
	for k,v in pairs(form) do
		body=body..[[Content-Disposition: form-data; name="]]..k.."\"\r\n\r\n"..v.."\r\n"
	end
	body=body.."----WebKitFormBoundary7MA4YWxkTrZu0gW"

	return httpc.request("POST", host, url, recvheader, header, body)
end

local function decode_func(c)
	return string.char(tonumber(c, 16))
end

local function decode(str)
	local str = str:gsub('+', ' ')
	return str:gsub("%%(..)", decode_func)
end

function httpc.url_decode(str)
	return decode(str)
end

function httpc.url_encode(str)
	return (string.gsub(str, "([^A-Za-z0-9_])", function(c)
		return string.format("%%%02X", string.byte(c))
	end))
end

return httpc
